package thread;

import java.util.concurrent.atomic.AtomicInteger;

public class ThreadDemo8 {

    public static void main(String[] args) throws InterruptedException{
        // 这些原子类，就是基于 CAS 实现了自增，自减操作，此时进行这类操作不加锁，也是线程安全的
        AtomicInteger count = new AtomicInteger(0);

        // 使用原子类来解决线程安全问题
        Thread t1 = new Thread(() -> {
            for (int i = 0; i < 5000; i++) {
                count.getAndIncrement();// 相当于是 count++
                //count.incrementAndGet();// ++count
                //count.getAndDecrement();// count--
                //count.decrementAndGet();// --count
            }
        });

        Thread t2 = new Thread(() -> {
            for (int i = 0; i < 5000; i++) {
                count.getAndIncrement();// 相当于是 count++
            }
        });

        t1.start();
        t2.start();
        t1.join();
        t2.join();

        System.out.println(count.get());
    }
}
